import { createRouter, createWebHistory } from 'vue-router'
import search from '../views/search/index.vue'
import goods from '../views/goods/index.vue'
import detail from '../views/detail/index.vue'
import Home from '../views/home/home.vue'
import Index from '../views/home/index.vue'
import Cla from '../views/home/cla.vue'
import Cart from '../views/home/cart.vue'
import My from '../views/home/my.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', redirect: '/home/cart' },
    {
      path: '/home', name: 'home', component: Home, children: [
        { path: 'index', name: 'index', component: Index },
        { path: 'cla', name: 'cla', component: Cla },
        { path: 'cart', name: 'cart', component: Cart },
        { path: 'my', name: 'my', component: My },
      ]
    },
    { path: '/search', name: 'search', component: search },
    { path: '/goods/:cat_name', name: 'goods', component: goods },
    { path: '/detail/:goods_id', name: 'detail', component: detail },
  ],
})

// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.fullPath == '/home/cart' || to.fullPath == '/home/my') {
    let token = localStorage.getItem('token');
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
export default router
